(function($, im, chat, doc) {
	
	
	var userinfo = app.getState();
	
	im.record = [];
	
	
	template.config('escape', false);


	window.addEventListener('sysMsg', function(event) {
		var rtinfo = event.detail;
		var sendtype = rtinfo.sendtype || 1;
		var sendmsg = {
			sender: rtinfo.sender,
			type: rtinfo.type,
			content: rtinfo.content
		};
		//.log(JSON.stringify(sendmsg));
		im.sendMsg(sendmsg, sendtype);

	});
	
	//侦听主窗口 我收消息
	window.addEventListener('refreshSay', function(event) {
		var rtinfo = event.detail;
		var fid = rtinfo['f_id'];
		
		//console.log(JSON.stringify(rtinfo));
		//console.log(im.roomId);
		//im.addOrUpdateserviceData(rtinfo);
		//var extras = app.isJson(rtinfo['extras']) ? JSON.parse(rtinfo['extras']) : {};
		
		var extras = rtinfo.extras;
		
		if (typeof extras === 'string') {
			extras = JSON.parse(extras);
		}
		
		if(im.roomType == 1) {
			//是自己
			if(fid != im.roomId) {
				return;
			}
			var header = app.avatar(fid, '../../static/images/logo.png');
			
			var emsg = {
				id: rtinfo['id'],
				header: header,
				sender: rtinfo['f_id'],
				type: rtinfo['r_type'],
				content: rtinfo['t_msg'],
				time: app.dateStr(rtinfo['add_time']),
				extras: extras || {}
			};
			//im.record.push(emsg);

		} else {
			if(rtinfo['t_id'] != im.roomId) {
				return;
			}
			//是自己
			if(rtinfo['f_id'] == im.uid) {
				return;
			}
			var header = app.avatar(fid, '../../static/images/qun.jpg');
			//var header = rtinfo['f_header'] ? serverurl + 'upload/avatar/' + fid + '.jpg' : '../../static/images/qun.jpg';
			var emsg = {
				id: rtinfo['id'],
				header: header,
				name: rtinfo['f_name'],
				sender: fid,
				type: rtinfo['r_type'],
				content: rtinfo['t_msg'],
				time: app.dateStr(rtinfo['add_time']),
				extras: extras || {}
			};
			//chat.setDataByField(im.roomId, 'msgnum', 0, 'room');

		}
		rendernewMsg(emsg);
		im.resizeMsgList();
	});
	
	
	//侦听主窗口 清空消息
	window.addEventListener('clear', function(event) {
		im.areaMsgList.innerHTML = '';
	});
	
	

	function rendernewMsg(msg) {
		if(msg.id) {
			var has = document.querySelector("[msg-id='" + msg.id + "']");
			if(has) {
				return;
			}
		}
		
		if (typeof msg.extras === 'string') {
			msg.extras = JSON.parse(msg.extras);
		}
		
		var tpl = template('msg-template', {
			"record": [msg],
			"header": msg.header
		});
		
		gatc.insertHtml(im.areaMsgList, tpl);
		
//		im.areaMsgList.innerHTML = im.areaMsgList.innerHTML + tpl;
		//im.areaMsgList.appendChild(tpl);
	}
	
	im.parseChatData = function(data) {
		var cache = [];
		//console.log(JSON.stringify(data));
		for(var p in data) {
			var val = data[p];
			var extras = val.extras;
			
			if (typeof extras === 'string') {
				try {
					extras = JSON.parse(extras);
				}
				catch (e) {
					console.error(JSON.stringify(val));
				}
			}
			
			/*
			if(val['f_header'] && val['f_header'].indexOf('upload/') !== -1) {
				var header = serverurl + 'upload/avatar/' + val['f_id'] + '.jpg';
			} else {
				var header = '../../static/images/1.png';
			}*/
			if(val['f_id'] == 1) {
				var header = '../../static/images/kefu3.png';
			} else {
				//var header = app.avatar(val['f_id'], '../../static/images/1.png');
				var header = dispimg + 'avatar/' + val['f_id'] + '.jpg';
			}

			if(val['f_id'] == im.uid) {
				val['f_id'] = 'self';
			}
			//console.log(val['extras']);
			//var extras = val['extras'] ? val['extras'] : {};
			//console.log(extras instanceof  Object);
			//var extras = (extras  instanceof  Object) ? extras : (app.isJson(extras) ? app.strToJson(extras) : extras);
			//var extras = app.isJson(extras) ? JSON.parse(extras) : extras;
			//var extras = app.isJson(extras) ? JSON.parse(extras) : {};
			//console.log(typeof extras);
			//if(extras != '[]' && typeof obj !== 'object') {
			//extras = extras.replace(/\\/g,'');
			//extras = JSON.parse(extras);
			//}
			//console.log(extras); 
			//return;
			var gz_avatar = app.getState();
			var pashdata = {
				id: val['id'],
				mid: val['m_id'],
				header: header,
				name: val['f_name'],
				sender: val['f_id'],
				type: val['r_type'],
				content: val['t_msg'],
				add_time: val['add_time'],
				time: app.dateStr(val['add_time']),
				extras: extras, // JSON.parse(val['extras']),
				myurls: dispimg + 'avatar/' + im.uid + '.jpg'
			};
			/*
			if(pashdata.mid){
				im.lastId = pashdata.mid;
			}*/
			im.record.push(pashdata);
			cache.push(pashdata);
			//console.log(JSON.stringify(pashdata));
		}
		if(cache.length < 1 && im.roomId == 1) {
			var now = Date.parse(new Date()) / 1000;
			var pashdata = {
				id: chat.getId('1'),
				mid: 0,
				header: '../../static/images/kefu3.png',
				name: 'GAT World',
				sender: 1,
				type: 'text',
				content: '让人人拥有数字资产，方便使用数字资产！',
				add_time: now,
				time: app.dateStr(now),
				extras: {}
			};
			/*
			if(pashdata.mid){
				im.lastId = pashdata.mid;
			}*/
			im.record.push(pashdata);
			im.record.index = 1;
			cache.push(pashdata);
		}
		return cache;
	}
	
	im.playsendSound = function(name) {
		var player = document.createElement('audio');
		player.src = '../../static/sound/' + name + '.mp3';
		player.volume = 1;
		player.loop = false;
		player.play();
	};

	//分页
	im.currentpage = 1;
	im.pagenum = 1;
	
	im.pageMgr = function(data) {
		var pagesize = 20,
			pagenum = 1,
			allnum = 0,
			cache = {};
		for(var p in data) {
			//cache.push(data[p]);
			allnum++;
		}
		im.pagenum = Math.ceil(allnum / pagesize); //向上取整,有小数就整数部分加1
		if(allnum < pagesize || im.pagenum == 1) {
			return data;
		}

		if(im.currentpage >= im.pagenum) {
			var breaknum = 0;
			var endnum = im.pagenum * pagesize - allnum;
		} else {
			var breaknum = allnum - im.currentpage * pagesize;
			var endnum = breaknum + pagesize;
		}
		//console.log(breaknum);
		//console.log(endnum);
		if(breaknum >= 0) {
			var i = 0;
			for(var p in data) {
				i++;
				if(i > breaknum && i <= endnum) {
					cache[p] = data[p];
				}
			}
			//console.log(JSON.stringify(cache));
			return cache;
		} else {
			console.log('error');
			return {};
		}

	};
	
	im.showKeyboard = function() {
		if($.os.ios) {
			var webView = plus.webview.currentWebview().nativeInstanceObject();
			webView.plusCallMethod({
				"setKeyboardDisplayRequiresUserAction": false
			});
		} else {
			// remove by yaozy 以下代码在显示系统输入框的时候很慢
//			var Context = plus.android.importClass("android.content.Context");
//			var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
//			var main = plus.android.runtimeMainActivity();
//			var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
//			imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);


			//console.log(document.activeElement.id);
			//imm.showSoftInput(main.getWindow().getDecorView(), InputMethodManager.SHOW_IMPLICIT);

		}
		document.getElementById("msg-text").focus();
	};


	function syssendMsg(msgInfo, totype) {

		if(totype === 0) {
			//console.log(totype);
			im.addnewMsg(msgInfo);
			im.sendMyMsg(msgInfo);
			im.toRobot(msgInfo);
		}
		if(totype === 1) {
			im.addnewMsg(msgInfo);
			im.sendMyMsg(msgInfo);
		}
		if(totype === 2) {
			im.toRobot(msgInfo);
		}
	}

	function tuling(msgInfo, totype) {
		//syssendMsg(msgInfo, 1);
		if(msgInfo.ftype == 'text') {

			var msgInfo = {
				id: im.uid + '-' + im.roomId + '-' + Date.parse(new Date()) / 1000,
				user_id: im.uid,
				user_name: userinfo.name,
				user_header: userinfo.avatar ? userinfo.avatar : '',
				room_id: 1,
				chat_name: im.chatName,
				header: im.header,
				msg: msgInfo.msg,
				ftype: msgInfo.ftype, //聊天类型
				ctype: 1, //聊天室类型
				extras: {}

			};
			im.addnewMsg(msgInfo);
			im.sendMyMsg(msgInfo);
			sendtuling(msgInfo);

		} else {
			if(totype == 2) {
				var apiurl = 'http://openapi.tuling123.com/openapi/api/v2';
				var uinfo = {
					"apiKey": "25a2f826dff6298220baf7be0008676c",
					"userId": im.uid
				};
				if(msgInfo.ftype == 'sound') {
					var postdata = {
						"reqType": 2,
						"perception": {
							"inputMedia": {
								"url": msgInfo.msg
							}
						},
						"userInfo": uinfo
					};
				} else if(msgInfo.ftype == 'image') {
					var postdata = {
						"reqType": 1,
						"perception": {
							"inputImage": {
								"url": msgInfo.msg
							}
						},
						"userInfo": uinfo
					};
				} else {
					var postdata = {
						"reqType": 0,
						"perception": {
							"inputText": {
								"text": msgInfo.msg
							}
						},
						"userInfo": uinfo
					};
				}
				mui.post(apiurl, JSON.stringify(postdata), function(res) {
					//console.log(JSON.stringify(res));
				});
			} else {
				im.addnewMsg(msgInfo);
				im.sendMyMsg(msgInfo);
			}
		}

	}

	function sendtuling(msgInfo) {
		var apiUrl = 'http://www.tuling123.com/openapi/api';
		$.getJSON(apiUrl, {
			"key": '25a2f826dff6298220baf7be0008676c',
			"info": msgInfo.msg,
			"userid": im.uid
		}, function(data) {
			//console.log(JSON.stringify(data));
			var msgInfo = {
				id: '1-' + im.uid + '-' + Date.parse(new Date()) / 1000,
				user_id: 1,
				user_name: 'GATCWorld',
				user_header: '../../static/images/kefu3.png',
				room_id: im.uid,
				chat_name: im.user_name,
				header: '../../static/images/kefu3.png',
				msg: data['text'],
				ftype: 'text', //聊天类型
				ctype: 1, //聊天室类型
				extras: {}

			};
			syssendMsg(msgInfo, 1);
			im.resizeMsgList();
		});
	}
	
	/**
	 * totype 0我发送然后对方接收 1只是我发送 2只是让对方接收
	 * @param {Object} msg
	 */
	im.sendMsg = function(msg, totype) {
		var totype = totype || 0;
		var extras = msg.extras;

		if (typeof extras !== 'string') {
			extras = extras == null ? '{}' : JSON.stringify(extras);
		}
		
		var msgInfo = {
			type: 'say',
			id: msg.id || chat.getId(im.roomId),
			user_id: im.uid,
			user_name: userinfo.name,
			user_header: userinfo.avatar ? userinfo.avatar : '',
			room_id: im.roomId,
			chat_name: im.chatName,
			header: im.header,
			msg: msg.content,
			ftype: msg.type, //聊天类型
			ctype: im.roomType, //聊天室类型,
			extras: extras

		};
		if(im.roomId == 1) {
			tuling(msgInfo, totype);
		} else {
			syssendMsg(msgInfo, totype);
		}
		//console.log(JSON.stringify(msgInfo));

	};
	
	im.closeFooterBox = function() {
		document.querySelector('#Gallery').style.display = 'none';
		document.querySelector('#biaoqingbao').style.display = 'none';
		document.querySelector('footer').style.bottom = '0px';
	};

	//var mainWin = plus.webview.getWebviewById(mainid);
	im.toRobot = function(msgInfo) {
		
		//msgInfo.extras = JSON.stringify(msgInfo.extras);
		mui.fire(im.mainWin, 'sendMsg', msgInfo);
		//main.evalJS("ws.send('"+JSON.stringify(msgInfo)+"')"); 
		/*
		mui.post(toUrl, msgInfo, function(res){
			if(!res.status) {
				mui.alert('发送失败！');
			}else{
				localStorage.setItem('newmsg', res.cid);
			}
		});*/
	};
	
	im.loginroom = function() {

		userinfo.type = 'loginroom';
		userinfo.roomId = im.roomId;
		userinfo.ctype = im.roomType;
		mui.fire(im.mainWin, 'loginroom', userinfo);
	}
	
	im.ajaxuploadImg = function(path) {
		var img = new Image();
		img.src = path;
		img.onload = function() {
			var that = this;
			//生成比例 
			var w = that.width,
				h = that.height,
				scale = w / h;
			w = 680 || w; //480  你想压缩到多大
			h = w / scale;

			//生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			canvas.setAttribute('width', w);
			canvas.setAttribute('height', h);
			ctx.drawImage(that, 0, 0, w, h);
			var base64 = canvas.toDataURL('image/jpeg', 1); //1z 表示图片质量，越低越模糊
			//console.log('go');
			//console.log(base64);
			var postdata = { //gz-修改
				file: base64,
				uid: im.uid,
				path: path
			};
			mui.ajax({
				url: upurl,
				data: postdata,
				async: true,
				dataType: 'json',
				crossDomain: true, //强制使用5+跨域
				type: 'post',
				timeout: 10000,
				success: function(res) {
					//console.log(res);
					console.log(JSON.stringify(res));
					//return;

					//console.log(res.status);
					if(res.status > 0) {
						res.src = res.surl;
						res.bsrc = res.url;

						im.sendMsg({
							type: 'image',
							content: res.src,
							extras: res
						}, 2);
						var el = document.querySelector("[src='" + path + "']");
						//res.src = serverurl + res.surl;
						//res.bsrc = serverurl + res.url;
						el.setAttribute('src', res.src);
						el.setAttribute('bsrc', res.bsrc);
						el.setAttribute('fname', res.name);
						el.setAttribute('fsize', res.size);
						el.setAttribute('ftype', res.type);
						var parent = el.parentNode.parentNode.parentNode;
						var id = parent.getAttribute('msg-id');
//						var extras = JSON.stringify(res);
						chat.edit(im.roomId, id, 'extras', res);
						chat.edit(im.roomId, id, 'content', res.src);
						//console.log(d.extras);
					} else {
						$.toast('发送失败！');
					}
				},
				error: function(xhr, type, errorThrown) {
					//console.log(JSON.stringify(xhr));
					//console.log(JSON.stringify(type));
					//console.log(xhr);
					console.log(type);
					console.log(JSON.stringify(errorThrown));
					//mui.toast('登录失败！');
					// 请求失败
				}
			});
			/*
			$.post(upurl, { //gz-修改
				file: base64,
				uid: im.uid,
				path: path
			}, function(res) {
				console.log(JSON.stringify(res));

				//console.log(res.status);
				if(res.status > 0) {
					res.src = serverurl + res.surl;
					res.bsrc = serverurl + res.url;

					im.sendMsg({
						type: 'image',
						content: res.src,
						extras: res
					}, 2);
					var el = document.querySelector("[src='" + path + "']");
					//res.src = serverurl + res.surl;
					//res.bsrc = serverurl + res.url;
					el.setAttribute('src', res.src);
					el.setAttribute('bsrc', res.bsrc);
					el.setAttribute('fname', res.name);
					el.setAttribute('fsize', res.size);
					el.setAttribute('ftype', res.type);
					var parent = el.parentNode.parentNode.parentNode;
					var id = parent.getAttribute('msg-id');
					var extras = JSON.stringify(res);
					chat.edit(im.roomId, id, 'extras', extras);
					chat.edit(im.roomId, id, 'content', res.src);
					//console.log(d.extras);
				} else {
					$.toast('发送失败！');
				}
			}, function(err) {
				console.log(JSON.stringify(err));
			});*/

		}
	}
	
	/**
	 * 我发消息,更新列表页和聊天页
	 * @param {Object} msgInfo
	 */
	im.addnewMsg = function(msgInfo) {

		//console.log();
		//im.addOrUpdateserviceData(msgInfo);

		var rtinfo = {
			id: msgInfo.id || chat.getId(im.roomId),
			f_id: msgInfo.user_id,
			f_name: msgInfo.user_name,
			f_header: msgInfo.user_header,
			t_header: msgInfo.header,
			t_name: msgInfo.chat_name,
			t_msg: msgInfo.msg,
			t_id: msgInfo.room_id,
			ctype: im.roomType,
			r_type: msgInfo.ftype,
			extras: msgInfo.extras, //JSON.stringify(msgInfo.extras),
			isread: 0,
			m_id: 0,
			add_time: Date.parse(new Date()) / 1000
		};
		//更新列表
		chat.set(im.roomId, rtinfo);
	};

	/**
	 * 发送消息 
	 * @param {Object} msgInfo
	 */
	im.sendMyMsg = function(msgInfo) {
		if(msgInfo.user_id == 1) {
			var head = '../../static/images/kefu3.png';
		} else {
			var head = app.avatar(im.uid, '../../static/images/1.png');
		}
		var gz_avatar = app.getState();

		var msg = {
			id: msgInfo.id || chat.getId(im.roomId),
			header: head,
			sender: msgInfo.user_id == im.uid ? 'self' : msgInfo.user_id,
			type: msgInfo.ftype,
			content: msgInfo.msg,
			add_time: msgInfo.add_time || Date.parse(new Date()) / 1000,
			time: app.dateStr(Date.parse(new Date()) / 1000),
			extras: msgInfo.extras,
			myurls: dispimg + 'avatar/' + im.uid + '.jpg'
		};
		rendernewMsg(msg);
		im.resizeMsgList();
	}

	
	im.getDatas = function() {
		//console.log(im.roomId);
		var data = chat.get(im.roomId);
		//console.log(JSON.stringify(data));
		//var parsedata = app.isJson(data) ? JSON.parse(data) : app.strToJson(data);
		if(data) {
//			im.lastId = data['lastId'] || 0;
			//return im.pageMgr(data['list']);
			return data['list'];
		} else {
			return [];
		}

		//return parsedata;
	}


	im.getServiceData = function() {
		//initServiceData();
		parsedata = im.getDatas();
		
		im.record.index = parsedata.length || 0;
		im.parseChatData(parsedata);
	}


	im.resizeMsgList = function() {
		im.imageViewer.findAllImage();
		//console.log(im.areaMsgList.offsetHeight);
		//console.log(im.areaMsgList.offsetHeight);
		//im.content.style.marginBottom = 15;
		im.areaMsgList.scrollTop = im.areaMsgList.scrollHeight + im.areaMsgList.offsetHeight;
	};


	function addChatListData(list, func) {
		if(list && list.length > 0) {
			var len = list.length;
			for(var i = 0; i < len; i++) {
				var msgInfo = list[i];
//				list[i]['lastId'] = msgInfo['m_id'];
				chat.set(im.roomId, msgInfo);
				//var sendid = im.roomType === 1 ? msgInfo['f_id'] : msgInfo['t_id'];
				var msg = {
					id: msgInfo.id || chat.getId(im.roomId),
					header: app.avatar(msgInfo['f_id'], '../../static/images/1.png'),
					sender: msgInfo['f_id'],
					type: msgInfo.r_type,
					content: msgInfo.t_msg,
					add_time: msgInfo.add_time || Date.parse(new Date()) / 1000,
					time: app.dateStr(Date.parse(new Date()) / 1000),
					extras: msgInfo.extras
				};
			}
			
			list = im.parseChatData(list);
			appendMessageList(list);
		}
	}
	
	
	function appendMessageList(list) {
	
		var host = im.areaMsgList;
		
		var html = template('msg-template', {
			record: list,
			header: im.header,
		});
		
		gatc.insertHtml(host, html);
		
		scrollToEnd(host);
		
		im.imageViewer = new $.ImageViewer('.msg-content-image', {
			dbl: false
		});
	}
	
	
	function refreshMessage() {
		var host = im.areaMsgList,
			record = im.record,
			index = record.index,
			html;
		
		if (index > 0)
		{
			html = template('msg-template', {
				record: record.slice(index - 20, index),
				header: im.header,
			});
			
			record.index -= 20;
			
			gatc.insertHtml(host, html, true);
			
			scrollToEnd(host);
			
			im.imageViewer = new $.ImageViewer('.msg-content-image', {
				dbl: false
			});
		}
	}
	
	
	function scrollToEnd(host, listen) {
		
		if (host.scrollTop !== host.scrollHeight) {
			host.onscroll = null;
			host.scrollTop = host.scrollHeight;
		}
		
		// 滚动时按需加载本地消息
		host.onscroll = scrollToRender;
		
		if (listen !== false) {
			// 延时解决滚不到底的问题
			setTimeout(function () {
				
				scrollToEnd(host, false)
				
			}, 1000)
		}
	}
	
	
	function scrollToRender() {
		if (this.scrollTop < 500) {
			refreshMessage();
		}
	}
	

	function checkRoomStatus() {
		if(im.uid == im.roomId) {
			mui.alert('你不能给自己聊天');
			mui.back();
		}
		if(im.roomId < 3) {
			return;
		}
		
		//console.log(im.lastId);
		//$.ajaxSettings.async = false;
		var updateurl = '?uid=' + im.uid + '&fid=' + im.roomId + '&lastid=' + chat.lastId(im.roomId);
		if(im.roomType == 1) {
			im.data_type = 'index';
			$.get(apiurl + 'chat/updatepersons' + updateurl, function(res) {
				if(res.status < 1 && im.uid != 2) {
					if(res.status < 0) {
						mui.alert('你们还不是好友关系');
						chat.del(im.roomId);
					} else {
						mui.alert('参数错误');
					}
					mui.back();
				} else {
					addChatListData(res.list);
				}
			});
		} else {
			im.data_type = 'room';
			$.get(apiurl + 'chat/updaterooms' + updateurl, function(res) {
				//console.log(JSON.stringify(res));
				if(res.status < 1 && im.uid != 2) {
					if(res.status < 0) {
						mui.alert('你已被移出房间');
						chat.del(im.roomId);
					} else {
						mui.alert('参数错误');
					}
					mui.back();
				} else {
					addChatListData(res.list);
				}
			});
		}
	}


	$.plusReady(function() {

		im.body = doc.querySelector('body');
		im.footer = doc.querySelector('footer');
		im.footerRight = doc.querySelector('.footer-left');
		im.footerLeft = doc.querySelector('.footer-right');
		im.btnMsgImage = doc.querySelector('#msg-type');
		im.boxMsgText = doc.querySelector('#msg-text');
		im.boxMsgSound = doc.querySelector('#msg-sound');
		im.btnMsgType = doc.querySelector('#msg-image');
		im.areaMsgList = doc.querySelector('#msg-list');
		im.boxSoundAlert = doc.querySelector('#sound-alert');
		im.h = doc.querySelector('#h');
		im.content = doc.querySelector('.mui-content');
		im.uid = userinfo.user_id; //我的 id
		im.user_name = userinfo.name;
//		im.lastId = 0;
		im.chat = chat;
		//plus.storage.removeItem(im.uid + 'chatdata');
		im.page = 1;
		var mainid = localStorage.getItem('mainpage');
		im.mainWin = plus.webview.getWebviewById(mainid);

		//im.ws = null;
		im.isios = mui.os.ios ? true : false;
		im.header = plus.webview.currentWebview().chatHeader;
		im.chatName = plus.webview.currentWebview().chatTitle;
		im.roomType = plus.webview.currentWebview().roomType;
		im.roomId = plus.webview.currentWebview().roomId; //说话对象
		if(im.roomType > 1) {
			var roomdata = chat.getRoom(im.roomId);
			if(roomdata && roomdata.info && roomdata.info.name) {
				im.chatName = roomdata.info.name;
			}
		}
		im.extraWin = {
			chatHeader: im.header,
			chatTitle: im.chatName,
			roomType: im.roomType,
			roomId: im.roomId
		};
		//console.log(im.chatName);
		//newmsg
		im.tomsgtype = plus.webview.currentWebview().tomsgtype;
		im.tomsgsender = plus.webview.currentWebview().tomsgsender;
		im.tomsgcontent = plus.webview.currentWebview().tomsgcontent;
		if(userinfo.avatar && userinfo.avatar.indexOf('upload') !== -1) {
			im.header = dispimg + 'avatar/' + im.uid + '.jpg';
		} else {
			im.header = '../../static/images/logo.png';
		}
		im.imageViewer = new $.ImageViewer('.msg-content-image', {
			dbl: false
		});

		if(im.tomsgsender) {
			var sendmsg = {
				sender: im.tomsgsender,
				type: im.tomsgtype,
				content: im.tomsgcontent
			};
			//im.record.push(sendmsg);
			im.sendMsg(sendmsg, 1);
		}
		$.init({
			swipeBack: true,
			gestureConfig: {
				tap: true, //默认为true
				doubletap: true, //默认为false
				longtap: true, //默认为false
				swipe: true, //默认为true
				drag: true, //默认为true
				hold: true, //默认为false，不监听
				release: true //默认为false，不监听
			},

			beforeback: function() {
				//关闭时候的一些操作
				//socket.onclose();
				//获得列表界面的webview  
				//var list = plus.webview.currentWebview().opener();
				var list = plus.webview.getWebviewById('chat.html');
				
				// add by yaozy 退出时清除未读消息数
				chat.clearnum(im.roomId);
				
				//触发列表界面的自定义事件（refresh）,从而进行数据刷新  
				mui.fire(list, 'refreshList', null);
				//返回true，继续页面关闭逻辑  
				return true;
			},
			/*pullRefresh: {
				container: "#msg-list", //下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
				down : {
			      style:'circle',//必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
			      color:'#2BD009', //可选，默认“#2BD009” 下拉刷新控件颜色
			      height:'50px',//可选,默认50px.下拉刷新控件的高度,
			      range:'100px', //可选 默认100px,控件可下拉拖拽的范围
			      offset:'60px', //可选 默认0px,下拉刷新控件的起始位置
			      auto: false,//可选,默认false.首次加载自动上拉刷新一次
			      callback :dragpage //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
			    }
			}*/
		});

		document.querySelector('.mui-title').innerHTML = im.chatName;

		plus.webview.currentWebview().setStyle({
			softinputMode: "adjustResize"
		});
		
		im.h.style.width = im.boxMsgText.offsetWidth + 'px';
		//alert(ui.boxMsgText.offsetWidth );
		im.footerPadding = im.footer.offsetHeight - im.boxMsgText.offsetHeight;

		im.getServiceData();
		refreshMessage();
		
		chat.clearnum(im.roomId);
		checkRoomStatus();
		
		//im.loginroom();
		window.addEventListener('resize', im.resizeMsgList, false);
		window.addEventListener('loaded', im.resizeMsgList, false);
		//var my = plus.webview.getSecondWebview();
		//console.log(JSON.stringify(my)); 
		//im.connect();
		/*
		$.back = function(){
			var list = plus.webview.getWebviewById('chat.html');
			mui.fire(list, 'refreshList', null);
			$.back();
		}*/
		doc.getElementById('chatback').addEventListener('tap', function() {
			mui.back();
			//console.log('3');
		});
		
	});


}(mui, window.im = {}, chat, document));